package fr.umlv.ig.MetroView;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JLabel;
import javax.swing.Timer;

import fr.umlv.ig.listener.TimeListener;

@SuppressWarnings("serial")
public class MinesTimerLabel extends JLabel {


	private final ArrayList<TimeListener> timeListeners = new ArrayList<TimeListener>();
	private boolean firing;
	private final Timer timer;
	private int time=0;

	public MinesTimerLabel () {
		super("0");
		timer = createTimer ();
	}

	private Timer createTimer () {
		ActionListener action = new ActionListener () {
			@Override
			public void actionPerformed(ActionEvent e) {
				setText(Integer.toString(time));
				time++;
				
			}
		};
		return new Timer (1000, action);
	}

	public void startTimer(){
		timer.start ();
	}

	public void pauseTimer() {
		timer.stop();
		fireTimerStopped();

	}

	public void restartTimer() {
		timer.restart();
	}

	public void reinitialise() {
		time=0;
	}

	public String getTime() {
		int seconds = time;
		int h= seconds/3600;
		int min = (seconds%3600)/60;
		int s = ((seconds%3600)%60);
		if (h==0) {
			if(min==0) {
				return s+"s";
			}
			else {
				return min+"min"+s+"s";
			}
		}
		else {
			return h+"h"+min+"min"+s+"s";
		}
	}

	public void addTimeListener(TimeListener t) {
		timeListeners.add(t);
	}

	public void removeTimeListener(TimeListener t) {
		if(firing) {
			throw new IllegalArgumentException("Cannot remove listener while fire... is using theme");
		}
		timeListeners.remove(t);
	}


	private void fireTimerStopped() {
		try {
			for(TimeListener t : timeListeners) {
				t.timeStop();
			}
		}
		finally {
			firing = false;
		}
	}
	
	
	public Integer getIntegerTime() {
		return time;
	}


}
